package com.client;

import com.codc.RequestEncoder;
import com.codc.ResponseDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.swing.*;
import java.net.InetSocketAddress;
import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/1/7.
 */
public class NettyClient {

    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    EventLoopGroup group = new NioEventLoopGroup();

    private static SwingClient swingClient;

    /**
     * 会话
     */
    private Channel channel;

    public void connect(int port, String host) throws Exception {

        // 配置客户端NIO线程组

        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ResponseDecoder(1024 * 1024, 4, 4));
                            ch.pipeline().addLast("requestEncoder",new RequestEncoder());
                            ch.pipeline().addLast("clientHandler",new ClientHandler(swingClient));
                            ch.pipeline().addLast(new ReadTimeoutHandler(50));
                        }
                    });

            // 发起异步连接操作
            // 发起异步连接操作
            ChannelFuture future = b.connect(
                    new InetSocketAddress(host, port)).sync();
            channel = future.channel();
            swingClient.channel = channel;

            channel.closeFuture().sync();

        }
        finally {

            swingClient.textArea1.append(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + " 连接失败!\n");
            // 所有资源释放完成之后，清空资源，再次发起重连操作
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                        try {
                            connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// 发起重连操作
                        } catch (Exception e) {

                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    public static void main(String[] args) throws Exception {
        swingClient = new SwingClient();

        JFrame frame = new JFrame("SwingClient");
        frame.setContentPane(swingClient.panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.setSize(500,600);

        new NettyClient().connect(NettyConstant.PORT, NettyConstant.REMOTEIP);

    }

}
